package com.example.eci_quartz.cloudcc.impl;

import com.example.eci_quartz.cloudcc.commcon.CommonMethod;
import com.example.eci_quartz.cloudcc.commcon.DataGroupUtil;
import com.example.eci_quartz.cloudcc.commcon.DateUtil;
import com.example.eci_quartz.cloudcc.dao.DefaultConnectionFactory;
import com.example.eci_quartz.cloudcc.dao.baseDao;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;


import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 *
 *同步设备信息
 */
public class EquipmentImpl2 extends baseDao {

	SimpleDateFormat sdf= new SimpleDateFormat("yyyyMMdd");
	SimpleDateFormat sdfY= new SimpleDateFormat("yyyy");
	SimpleDateFormat sdfM= new SimpleDateFormat("MMdd");
	static String binding = InsertXMInfo();
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static String upsertEquipment(){
		List<Map> updatelist =null;
		List<Map> insertlist =null;
		Connection conn =null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
		Calendar cal=Calendar.getInstance();
	    cal.set(Calendar.DATE,cal.get(Calendar.DATE)-1200);
	    String firstDay=format.format(cal.getTime());

	    Calendar cal2=Calendar.getInstance();
	    cal2.set(Calendar.DATE,cal2.get(Calendar.DATE)-501);
	    String newDate=format.format(cal2.getTime());
		String info = "false";
		Map<String,Map> rsMap=null;
		Map<String, Map> orderMap =null;
		/*
		 * EQPDATE  设备创建时间
		 * EQPCHG   设备更新时间
		 * CSADATE  CSA创建日期
		 * CSATIME  CSA创建时间
		 * CSACHGD  CSA更新日期
		 * CSACHGT  CSA更新时间
		 * EPPDATE  EPP创建时间
		 * EPPCHG   EPP更新时间
		 */
		String sql="select * FROM LIBJ49FSMS.EQPTNEW T"
 				+" WHERE T.LSMN8 BETWEEN '"+firstDay+"' AND '"+newDate+"'";
		try {
			conn= new DefaultConnectionFactory().getConnection();
			pstmt = conn.prepareStatement(sql);
			rs = pstmt.executeQuery();
			orderMap=new HashMap<String, Map>();// map<销售订单编号，销售订单对象值>
			rsMap=new HashMap<String,Map>();//map<零件号，零件数据>从DBS查询出来的
			String eqmfs2s="";//设备序列号数组
			String khbhs="";//客户数组
			int count=1;
			if (rs != null) {
				while (rs.next()) {
					Map mapObj=new HashMap();
 					//客户代码
 					String khbh=(rs.getString("CUNO") == null ? "" : rs.getString("CUNO")+"").trim();
 					if(khbh!=null&&!"".equals(khbh)){
 						mapObj.put("khbh",khbh);
 					}
 					//设备序列号
 					String eqmfs2=(rs.getString("EQMFS2") == null ? "" : rs.getString("EQMFS2")+ "").trim();
 					if(eqmfs2!=null && !"".equals(eqmfs2)){
 						mapObj.put("name", eqmfs2);
 					}
 					mapObj.put("sfjktb", 1);
 					//设备型号 EQMFM2
 					mapObj.put("sbxh",(rs.getString("DSPMDL") == null ? "" : rs.getString("DSPMDL")+ "").trim());
 					mapObj.put("divi",(rs.getString("DIVI") == null ? "" : rs.getString("DIVI")+"").trim());
 					//省份
 					mapObj.put("PRONAME",(rs.getString("PRONAME") == null ? "" : rs.getString("PRONAME")+ "").trim());
 					//交机日期
 					mapObj.put("jjrq",DateUtil.getDatetoStringUtil((rs.getString("DTDLV8") == null ? "" : rs.getString("DTDLV8")+ "").trim()));
 					//最后维护日期
 					mapObj.put("zhwhrq",DateUtil.getDatetoStringUtil((rs.getString("LSMN8") == null ? "" : rs.getString("LSMN8")+ "").trim()));

 					//设备状态
 					String sbzt=(rs.getString("PRHFMC") == null ? "" : rs.getString("PRHFMC")+ "").trim();
 					if(sbzt!=null&&!"".equals(sbzt)&&!sbzt.equals("null")) {
 						mapObj.put("sbzt","Active-"+sbzt);
 					}else{
 						mapObj.put("sbzt","Active-ECIM");
 					}
 					//品牌
 					mapObj.put("pp",(rs.getString("EQMFCD") == null ? "" : rs.getString("EQMFCD")+ "").trim());
 					//活跃度
 					mapObj.put("TERRI",(rs.getString("TERRI") == null ? "" : rs.getString("TERRI")+ "").trim());

 					//dbs创建日期
 					mapObj.put("dbscjsj",DateUtil.getDatetoStringUtil((rs.getString("DTSYS8") == null ? "" : rs.getString("DTSYS8")+ "").trim()));
 					//修改日期
 					mapObj.put("dbsxgsj",DateUtil.getDatetoStringUtil((rs.getString("LSMN8") == null ? "" : rs.getString("LSMN8")+ "").trim()));
 					if(eqmfs2!=null&&!"".equals(eqmfs2)) {
 						//设备数组
 						eqmfs2s+="'"+eqmfs2+"',";
 						//客户数组
 						khbhs+="'"+khbh+"',";
 						//eqmfs2是否有重复
 						rsMap.put(eqmfs2, mapObj);
 					}
			}

			 //判断标准工时编号是否存在
		     if(eqmfs2s!=null&&!"".equals(eqmfs2s)){
		    	 orderMap=getsbglMap(eqmfs2s);
			 }
			//判断设备是新增还是更新
			Map khMap=null;
			if(rsMap.size()>0&&rsMap!=null){
				updatelist = new ArrayList<Map>();
				insertlist = new ArrayList<Map>();
			   if(khbhs!=null&&!khbhs.equals("")) {
				   khMap= getAccountMap(khbhs.substring(0,khbhs.length()-1));//查询客户集合
			   }
			   for(String eqmfs2:rsMap.keySet()){
				   Map ljObj=rsMap.get(eqmfs2);//获取DBS中的序列号
				   if (orderMap.containsKey(eqmfs2)) {//更新设备信息
					  Map sb= orderMap.get(eqmfs2);
					   Map acct=(Map)khMap.get(ljObj.get("khbh"));
					   if(acct!=null&&!"".equals(acct)) {
						    ljObj.put("khmc", (acct.get("id") == null ? "" : acct.get("id").toString()).trim());
						    String csrfgry=(acct.get("csrfgry")== null ?"" : acct.get("csrfgry").toString()).trim();
						    if(csrfgry!=null&&!"".equals(csrfgry)&&!csrfgry.equals("null")) {
						    	ljObj.put("csrfgry", csrfgry);
						    }else {
						    	ljObj.put("csrfgry", "");
						    }
					   }
					   /*
					    *①从CLoudcc中获取省份，如果不为空，就获取CLoudcc赋值，
					    *②如果为空，就引用dbs数据，不修改上面内容。
					    * */
					   String PRONAME=sb.get("PRONAME")+"";//省份
					   String sbzt=sb.get("sbzt")+"";//设备状态
					   //省份
					   if(!"".equals(PRONAME)){
						   ljObj.put("PRONAME",PRONAME);
					   }
					   //设备状态
					   if(!"".equals(sbzt)){
						   ljObj.put("sbzt",sbzt);
					   }
					   ljObj.put("id",sb.get("id"));
					   updatelist.add(ljObj);//更新设备信息
					}else{//新建设备信息
						  Map acct=(Map) khMap.get(ljObj.get("khbh"));
						   if(acct!=null&&!"".equals(acct)) {
							    ljObj.put("khmc", (acct.get("id") == null ? "" : acct.get("id").toString()).trim());
							    String csrfgry=(acct.get("csrfgry") == null ? "" : acct.get("csrfgry").toString()).trim();
							    if(csrfgry!=null&&!"".equals(csrfgry)&&!csrfgry.equals("null")) {
							    	ljObj.put("csrfgry", csrfgry);
							    }else {
							    	ljObj.put("csrfgry", "");
							    }
						   }
						   insertlist.add(ljObj);//新增设备信息
					 }
				 }
			}
			//插入新的设备信息
			if (insertlist!=null&&insertlist.size()>0) {
				Map<Integer,List> map = DataGroupUtil.dataOneGroup(insertlist); //用map存起来新的分组后数据,每100条一组
				if(map.size()>0){
					for(Integer m:map.keySet()){
						List amList=map.get(m);
						JSONArray jsonArrayInsert = JSONArray.fromObject(amList);
						String jsonstr=jsonArrayInsert.toString();
						jsonstr = java.net.URLEncoder.encode(jsonstr, "UTF-8");
						String data_insert = "serviceName=insert&objectApiName=sbgl&data="+jsonstr+"&binding=";//insertLt批量插入，不走触发器
						String insertInfo=operate(data_insert+ binding);//执行CRM系统插入操作insert
				        //判断binding是否失效，如果失效，就重新获取
						JSONObject fromObject =null;
						String result ="";
						if(CommonMethod.isJSONValid(insertInfo)){
							fromObject = JSONObject.fromObject(insertInfo);
							result= fromObject.getString("result")==null?"":fromObject.getString("result");
						}
						if(!"true".equals(result)){
							binding = InsertXMInfo();
							insertInfo=operate(data_insert+binding);
						}
					    info="insert_success";
					}
				}
			}
			//更新系统中的设备信息
			if (updatelist!=null&&updatelist.size()>0) {
				Map<Integer,List> map = DataGroupUtil.dataGroup(updatelist);
				if(map.size()>0){
					for(Integer m:map.keySet()){
						List amList=map.get(m);
						JSONArray jsonArrayUpdate = JSONArray.fromObject(amList);
						String jsonstr_update=jsonArrayUpdate.toString();
						jsonstr_update = java.net.URLEncoder.encode(jsonstr_update, "UTF-8");
						String data_update = "serviceName=updateLt&objectApiName=sbgl" +
								"&data="+jsonstr_update+"&binding=";//updateLt批量更新，不走触发器
						String updateInfo=operate(data_update+binding);//执行CRM更新操作update
				        //判断binding是否失效，如果失效，就重新获取
						JSONObject fromObject =null;
						String result ="";
						if(CommonMethod.isJSONValid(updateInfo)){
							fromObject = JSONObject.fromObject(updateInfo);
							result= fromObject.getString("result")==null?"":fromObject.getString("result");
						}
						if(!"true".equals(result)){
							binding = InsertXMInfo();
							updateInfo=operate(data_update+binding);
						}
			            info="update_success";
					}
				}
			}
		}
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			try {
				if (rs != null) {
					rs.close();
					rs = null;
				}
				if (pstmt != null) {
					pstmt.close();
					pstmt = null;
				}
				if (conn != null) {
					conn.close();
					conn = null;
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return info;
	}

	public static Map<String, Object> getAccountMap(String khbhs){
		String data_query = "serviceName=cqlQuery&objectApiName=Account&expressions="
				+ "select id,name,khdm,csrfgry from Account where khdm is not null and is_deleted='0' "
				+ "and khdm in ("+khbhs+") &binding=";//查询客户信息
		String khinfo = "";//查询返回来的值
		String kh_datas = "";//查询成功返回来的数据
		Map<String, Object> khMap =null;
		try {
			khMap = new HashMap<String, Object>();// map<客户编号，客户对象值>
			khinfo = operate(data_query+binding);//通过http方式调用咱们平台的查询方法
	        //判断binding是否失效，如果失效，就重新获取
			JSONObject fromObject =null;
			String result ="";
			if(CommonMethod.isJSONValid(khinfo)){
				fromObject = JSONObject.fromObject(khinfo);
				result= fromObject.getString("result")==null?"":fromObject.getString("result");
			}
			if(!"true".equals(result)){
				binding = InsertXMInfo();
				khinfo=operate(data_query+binding);
			}

			String returninfo = "[" + khinfo + "]";// 手动转换成json格式，方便取值
			if (!"[]".equals(returninfo)&&khinfo!=null) {
				JSONArray brand_list = JSONArray.fromObject(returninfo);
				if (brand_list != null) {
					for (int j = 0; j < brand_list.size(); j++) {
						JSONObject brandInfo = (JSONObject) brand_list.get(j);
						String Result = brandInfo.get("result") == null ? ""
								: brandInfo.get("result") + "";// 获取返回值
						String date = brandInfo.get("data") == null ? ""
								: brandInfo.get("data") + "";// 获取查询结果的返回值
						if ("true".equals(Result)) {
							kh_datas = date;
						}
					}
				}
			}
			// 查询crm系统中客户的信息并存入到map中
			if (!"[]".equals(kh_datas)&&!"".equals(kh_datas)) {
				JSONArray datas_list = JSONArray.fromObject(kh_datas);
				if (datas_list != null) {
					for (int i = 0; i < datas_list.size(); i++) {
						JSONObject accObj = (JSONObject) datas_list.get(i);
						String khdm = accObj.get("khdm") == null? "" : accObj.get("khdm")+ "";
						if (!"".equals(khdm)&&khdm!=null) {
							khMap.put(khdm, accObj);
						}
					}
				}
		    }
		}catch (Exception e) {
		}
		return khMap;
	}

	@SuppressWarnings("rawtypes")
	public static Map<String, Map> getsbglMap (String eqmfs2s) throws Exception {
		Map<String, Map> sbMap = new HashMap<String, Map>();// map<销售订单编号，销售订单对象值>
		if(eqmfs2s!=null&&!"".equals(eqmfs2s)) {
			String orderinfo = "";//查询返回来的值
			String order_datas = "";//查询成功返回来的数据
			//查询系统中全部的设备管理
			String data_query = "serviceName=cqlQuery&objectApiName=sbgl" +
					"&expressions=select l.id,l.name,l.PRONAME,l.sbzt from sbgl l " +
					"where l.name is not null and l.name in ("+eqmfs2s.substring(0,eqmfs2s.length()-1)+")  " +
					"and l.is_deleted='0'&binding=";
			orderinfo = operate(data_query+ binding);
	        //判断binding是否失效，如果失效，就重新获取
			JSONObject fromObject =null;
			String result ="";
			if(CommonMethod.isJSONValid(orderinfo)){
				fromObject = JSONObject.fromObject(orderinfo);
				result= fromObject.getString("result")==null?"":fromObject.getString("result");
			}
			if(!"true".equals(result)){
				binding = InsertXMInfo();
				orderinfo=operate(data_query+binding);
			}
			String returninfo = "["+orderinfo+"]";// 手动转换成json格式，方便取值
			if (!"[]".equals(returninfo)&&orderinfo!=null) {
				JSONArray brand_list = JSONArray.fromObject(returninfo);
				if (brand_list != null) {
					for (int j = 0; j < brand_list.size(); j++) {
						JSONObject brandInfo = (JSONObject) brand_list.get(j);
						String Result = brandInfo.get("result") == null ? ""
								: brandInfo.get("result") + "";// 获取返回值
						String date = brandInfo.get("data") == null ? ""
								: brandInfo.get("data") + "";// 获取返回值
						if ("true".equals(Result)) {
							order_datas = date;
						}
					}
				}
			}
			//查询CRM系统中零件库存的信息并存入到map中
			if (order_datas != "[]"&&!"".equals(order_datas)) {
				JSONArray datas_list = JSONArray.fromObject(order_datas);
				if (datas_list != null) {
					for (int i = 0; i < datas_list.size(); i++) {
						JSONObject accObj = (JSONObject) datas_list.get(i);
						JSONObject order_newObj = new JSONObject();//新的json，只存id，编号
						//设备序列号
						//设备序列号
					    String eqmfs2= (accObj.get("name")==null? "" : accObj.get("name").toString()).trim();
					    String PRONAME= (accObj.get("PRONAME")==null? "" : accObj.get("PRONAME").toString()).trim();
					    String sbzt= (accObj.get("sbzt")==null? "" : accObj.get("sbzt").toString()).trim();
					    if(eqmfs2!=null&&!"".equals(eqmfs2)){
					    	order_newObj.put("id", accObj.get("id"));
							order_newObj.put("eqmfs2", eqmfs2);
							order_newObj.put("PRONAME", PRONAME);
							order_newObj.put("sbzt", sbzt);
							sbMap.put(eqmfs2,order_newObj);
					    }
					}
				}
			}
		}
		return sbMap;
	}
}
